package com.stationpc.androidtvrecents;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class TasksUtils {
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void removeTask(Context context, String packageName){
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(20);
        for (ActivityManager.RunningTaskInfo task:
                 tasks) {
            if(task.baseActivity != null && packageName.equals(task.baseActivity.getPackageName())){
                removeTask(task.taskId);
                return;
            }

        }


    }
    public static void removeTask(int taskid) {
        Class<?> cls = null;
        try {
            cls = Class.forName("android.app.ActivityTaskManager");
            @SuppressLint("BlockedPrivateApi") java.lang.reflect.Method services = cls.getDeclaredMethod("getService");
            Object iam = services.invoke(null);

            java.lang.reflect.Method removeTaskMethod = iam.getClass().getDeclaredMethod("removeTask", int.class);
            removeTaskMethod.setAccessible(true);

            removeTaskMethod.invoke(iam, taskid);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

}